#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import signal
import time
import argparse

class MESManager:
    def __init__(self):
        self.base_dir = '/home/ubuntu/zlymes/mesmaster'
        self.conda_env = 'mes'
        self.services = {
            'basic': {
                'port': 8004,
                'settings': 'settings_mes_basic',
                'name': '基础MES服务',
                'pid_file': '/tmp/mes_basic.pid',
                'log_file': '/tmp/mes_basic.log'
            },
            'full': {
                'port': 8005,
                'settings': 'settings_full_mes',
                'name': '完整MES服务',
                'pid_file': '/tmp/mes_full.pid',
                'log_file': '/tmp/mes_full.log'
            },
            'admin': {
                'port': 8006,
                'settings': 'settings_django_with_mes',
                'name': 'Django管理服务',
                'pid_file': '/tmp/mes_admin.pid',
                'log_file': '/tmp/mes_admin.log'
            }
        }
    
    def get_conda_command(self):
        """获取conda激活命令"""
        return f"source ~/miniconda3/etc/profile.d/conda.sh && conda activate {self.conda_env}"
    
    def run_command(self, cmd, capture_output=True):
        """运行命令"""
        try:
            if capture_output:
                result = subprocess.run(cmd, shell=True, capture_output=True, text=True, cwd=self.base_dir)
                return result.returncode == 0, result.stdout, result.stderr
            else:
                result = subprocess.run(cmd, shell=True, cwd=self.base_dir)
                return result.returncode == 0, "", ""
        except Exception as e:
            return False, "", str(e)
    
    def check_django(self):
        """检查Django环境"""
        print("检查Django环境...")
        cmd = f"{self.get_conda_command()} && python -c 'import django; print(\"Django版本:\", django.VERSION)'"
        success, stdout, stderr = self.run_command(cmd)
        if success:
            print(f"✓ {stdout.strip()}")
        else:
            print(f"✗ Django检查失败: {stderr}")
        return success
    
    def check_settings(self, settings_name):
        """检查Django设置"""
        print(f"检查设置文件: {settings_name}")
        cmd = f"{self.get_conda_command()} && python manage.py check --settings={settings_name}"
        success, stdout, stderr = self.run_command(cmd)
        if success:
            print(f"✓ 设置文件检查通过")
        else:
            print(f"✗ 设置文件检查失败: {stderr}")
        return success
    
    def migrate_database(self, settings_name):
        """运行数据库迁移"""
        print(f"运行数据库迁移: {settings_name}")
        cmd = f"{self.get_conda_command()} && python manage.py migrate --settings={settings_name}"
        success, stdout, stderr = self.run_command(cmd)
        if success:
            print(f"✓ 数据库迁移完成")
        else:
            print(f"✗ 数据库迁移失败: {stderr}")
        return success
    
    def create_superuser(self, settings_name):
        """创建超级用户"""
        print("检查/创建超级用户...")
        cmd = f'''{self.get_conda_command()} && python manage.py shell --settings={settings_name} -c "
from django.contrib.auth.models import User
if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
    print('创建超级用户: admin/admin123')
else:
    print('超级用户已存在')
"'''
        success, stdout, stderr = self.run_command(cmd)
        if success:
            print(f"✓ {stdout.strip()}")
        else:
            print(f"✗ 超级用户创建失败: {stderr}")
        return success
    
    def start_service(self, service_name):
        """启动单个服务"""
        if service_name not in self.services:
            print(f"未知服务: {service_name}")
            return False
        
        service = self.services[service_name]
        print(f"启动{service['name']}...")
        
        # 检查服务是否已经在运行
        if self.is_service_running(service_name):
            print(f"✓ {service['name']}已在运行")
            return True
        
        # 检查设置文件
        if not self.check_settings(service['settings']):
            return False
        
        # 运行迁移
        if not self.migrate_database(service['settings']):
            return False
        
        # 创建超级用户
        if not self.create_superuser(service['settings']):
            return False
        
        # 启动服务
        cmd = f"""{self.get_conda_command()} && python manage.py runserver 0.0.0.0:{service['port']} --settings={service['settings']} > {service['log_file']} 2>&1 &"""
        
        # 获取PID
        full_cmd = f"cd {self.base_dir} && {cmd} echo $! > {service['pid_file']}"
        
        success, stdout, stderr = self.run_command(full_cmd, capture_output=False)
        
        if success:
            time.sleep(2)  # 等待服务启动
            if self.is_service_running(service_name):
                print(f"✓ {service['name']}启动成功")
                print(f"  - 端口: {service['port']}")
                print(f"  - 日志: {service['log_file']}")
                print(f"  - 访问: http://175.27.138.86:{service['port']}/")
                print(f"  - 管理: http://175.27.138.86:{service['port']}/admin/")
                return True
            else:
                print(f"✗ {service['name']}启动失败")
                self.show_service_log(service_name)
                return False
        else:
            print(f"✗ {service['name']}启动命令失败")
            return False
    
    def stop_service(self, service_name):
        """停止单个服务"""
        if service_name not in self.services:
            print(f"未知服务: {service_name}")
            return False
        
        service = self.services[service_name]
        print(f"停止{service['name']}...")
        
        # 通过端口查找进程
        cmd = f"lsof -t -i:{service['port']}"
        success, stdout, stderr = self.run_command(cmd)
        
        if success and stdout.strip():
            pids = stdout.strip().split('\n')
            for pid in pids:
                try:
                    os.kill(int(pid), signal.SIGTERM)
                    print(f"✓ 停止进程 PID: {pid}")
                except ProcessLookupError:
                    print(f"进程 {pid} 不存在")
                except Exception as e:
                    print(f"停止进程失败: {e}")
        else:
            print(f"✓ {service['name']}未在运行")
        
        # 清理PID文件
        if os.path.exists(service['pid_file']):
            os.remove(service['pid_file'])
        
        return True
    
    def is_service_running(self, service_name):
        """检查服务是否在运行"""
        if service_name not in self.services:
            return False
        
        service = self.services[service_name]
        cmd = f"lsof -t -i:{service['port']}"
        success, stdout, stderr = self.run_command(cmd)
        
        return success and stdout.strip()
    
    def show_service_status(self):
        """显示所有服务状态"""
        print("\n=== MES服务状态 ===")
        for service_name, service in self.services.items():
            status = "运行中" if self.is_service_running(service_name) else "已停止"
            print(f"{service['name']}: {status} (端口: {service['port']})")
    
    def show_service_log(self, service_name, lines=20):
        """显示服务日志"""
        if service_name not in self.services:
            print(f"未知服务: {service_name}")
            return
        
        service = self.services[service_name]
        log_file = service['log_file']
        
        if os.path.exists(log_file):
            print(f"\n=== {service['name']}日志 (最后{lines}行) ===")
            cmd = f"tail -n {lines} {log_file}"
            success, stdout, stderr = self.run_command(cmd)
            if success:
                print(stdout)
            else:
                print(f"读取日志失败: {stderr}")
        else:
            print(f"{service['name']}日志文件不存在: {log_file}")
    
    def start_all(self):
        """启动所有服务"""
        print("=== 启动所有MES服务 ===")
        
        # 先检查Django环境
        if not self.check_django():
            print("Django环境检查失败，无法启动服务")
            return False
        
        # 启动所有服务
        success_count = 0
        for service_name in self.services:
            if self.start_service(service_name):
                success_count += 1
        
        print(f"\n=== 启动完成 ({success_count}/{len(self.services)}) ===")
        if success_count == len(self.services):
            print("所有服务启动成功！")
            print("\n访问地址:")
            for service_name, service in self.services.items():
                print(f"- {service['name']}: http://175.27.138.86:{service['port']}/")
                print(f"  管理后台: http://175.27.138.86:{service['port']}/admin/")
            print("\n管理员账户: admin / admin123")
        else:
            print("部分服务启动失败，请检查日志")
        
        return success_count == len(self.services)
    
    def stop_all(self):
        """停止所有服务"""
        print("=== 停止所有MES服务 ===")
        for service_name in self.services:
            self.stop_service(service_name)
        print("所有服务已停止")
    
    def restart_all(self):
        """重启所有服务"""
        print("=== 重启所有MES服务 ===")
        self.stop_all()
        time.sleep(2)
        self.start_all()

def main():
    parser = argparse.ArgumentParser(description='MES服务管理器')
    parser.add_argument('action', choices=['start', 'stop', 'restart', 'status', 'log'], 
                       help='操作类型')
    parser.add_argument('--service', choices=['basic', 'full', 'admin'], 
                       help='指定服务 (如果不指定则操作所有服务)')
    parser.add_argument('--lines', type=int, default=20, 
                       help='显示日志行数 (仅用于log操作)')
    
    args = parser.parse_args()
    
    manager = MESManager()
    
    if args.action == 'start':
        if args.service:
            manager.start_service(args.service)
        else:
            manager.start_all()
    
    elif args.action == 'stop':
        if args.service:
            manager.stop_service(args.service)
        else:
            manager.stop_all()
    
    elif args.action == 'restart':
        if args.service:
            manager.stop_service(args.service)
            time.sleep(2)
            manager.start_service(args.service)
        else:
            manager.restart_all()
    
    elif args.action == 'status':
        manager.show_service_status()
    
    elif args.action == 'log':
        if args.service:
            manager.show_service_log(args.service, args.lines)
        else:
            for service_name in manager.services:
                manager.show_service_log(service_name, args.lines)

if __name__ == '__main__':
    main() 